import 'dart:convert';

import 'package:logger/logger.dart';

import '../dao/ImCollectDao.dart';
import '../dao/ImMessageDao.dart';
import '../pojo/ImPojo.dart';
import '../socket/dto/business/PullData2.dart';
import 'BaseService.dart';

class ImCollectService extends BaseService {

  final _logger = Logger(printer: PrettyPrinter(),);

  Future<List<ImCollect>> saveOrUpdates(String userId, List<CollectInfoItem> collectInfoItemList) async {
    if (collectInfoItemList.isEmpty) return Future.value([]);
    final collectDao = ImCollectDao();
    var imCollects = collectInfoItemList.map((configItem)=>_toCollect(userId, configItem)).toList();

    Set<ImCollect> insertImCollectSet = Set();
    Set<ImCollect> updateImCollectSet = Set();

    for(var imCollect in imCollects) {
      ImCollect? dbCollect = await collectDao.getByKey(imCollect.userId, imCollect.sessionId, imCollect.messageId);
      if (dbCollect == null) {
        insertImCollectSet.add(imCollect);
      } else {
        imCollect.id = dbCollect.id;
        updateImCollectSet.add(imCollect);
      }
    }
    if (insertImCollectSet.isNotEmpty) {
      await collectDao.batchInserts(insertImCollectSet.toList());
    }
    if (updateImCollectSet.isNotEmpty) {
      await collectDao.batchUpdates(updateImCollectSet.toList());
    }

    // todo 下载附件
    // downAttachFile(userId, imCollectList);

    return imCollects;
  }

  ImCollect buildCollectFromMessage(String userId, ImMessage imMessage) {
    var collect = ImCollect(userId: userId, messageId: imMessage.serverId!, sessionId: imMessage.imSession!.serverId!,
        messageType: imMessage.messageType!, content: imMessage.content, status: ImCollectStatus.enable);
    var collectContent = ImCollectContent(content: imMessage.content??'', fromUserId: imMessage.fromUserId,
        messageId: imMessage.serverId!, messageType: imMessage.messageType!);
    collectContent.fileContent = imMessage.ext;
    collect.collectContent = collectContent;
    collect.content = jsonEncode(collectContent);
    collect.message = imMessage;
    return collect;
  }

  ImCollect _toCollect(String userId, CollectInfoItem collectItem) {
    ImCollect collect = ImCollect(messageId: collectItem.messageId,
      sessionId: collectItem.sessionId,
      userId: userId,
      content: collectItem.content,
      messageType: ImMessageType.ofName(collectItem.messageType.name),
      status: ImCollectStatus.ofValue(collectItem.status.value),
    );
    collect.serverId = collectItem.serverId;
    collect.labelIds = collectItem.labelIds;

    buildContent(userId, collect);
    return collect;
  }

  void buildContent(String userId, ImCollect collect) async {
    String messageId = collect.messageId;
    final messageDao = ImMessageDao();
    ImMessage? imMessage = await messageDao.getByServerIdAndUserId(messageId, userId);
    // 为空时，需要拉取消息
    if (imMessage != null) {
      ImCollectContent collectContent = ImCollectContent(messageId: imMessage!.serverId!,
          messageType: imMessage.messageType,
          fromUserId: imMessage.fromUserId,
          content: imMessage.content
      );

      collectContent.messageTime = collect.createTime;
      collectContent.groupCode = imMessage.groupCode;
      collectContent.toUserId = imMessage.toUserId;
      collectContent.fileContent = imMessage.ext;
      collect.content = collectContent.toString();
    }
  }
}